﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Net.Fan.SmallPig.DataAccess;
using System.Data;
using Net.Fan.SmallPig.Common;

namespace Net.Fan.SmallPig.BusinessRules
{
    public class SystemSettingBiz
    {

        public static List<string> GetUnits()
        {
            DataRow uDr = SystemSettingDA.GetSetting("Units");
            string s = uDr["Value"] as string;
            string[] ss = s.Split(new char[] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries);
            List<string> units = new List<string>(ss);
            //units.Insert(0, null);
            return units;
        }

        private static string GetPK()
        {
            DataRow pk = SystemSettingDA.GetSetting("PK");

            if (pk != null)
            {
                string s = pk["Value"] as string;
                return s;
            }
            else
            {
                return null;
            }
        }


        public static bool CheckPK()
        {
            string pk = GetPK();

            return CheckPK(pk);

        }

        public static bool CheckPK(string pk)
        {
            if (string.IsNullOrEmpty(pk) || pk.Length != 20)
            {
                return false;
            }
            else
            {
                string machineId = SN.GetMachineId();
                string s1 = machineId.Substring(0, machineId.Length / 2);
                string s2 = machineId.Substring(machineId.Length / 2);
                string tmp = s2 + "fdp" + s1 + "fdy";
                string newString = StringUtils.SHA1(tmp);

                for (int i = 0; i < newString.Length; i = i + 2)
                {
                    if (newString[i] != pk[i / 2])
                    {
                        return false;
                    }
                }
                return true;
            }
        }

        public static void SavePK(string pk)
        {
            SystemSettingDA.SetSetting("PK", pk);
        }
    }
}
